import MusicPlayer from './src/index'
import { createApp } from 'vue'
import { getSongInfo } from 'Api/song'
import { createImageUrl, downloadFn } from 'Utils/utils'

// 插入组件
const insertComponent = () => {
    const dom = document.createElement('div')
    document.body.appendChild(dom)
    const Music = createApp({
        ...MusicPlayer,
        methods: {
            // 上一曲
            preFn () {
                MusicPlayer.pre()
            },
            // 下一曲
            nextFn () {
                MusicPlayer.next()
            },
            downloadFn () {
                downloadFn()
            }
        }
    }).mount(dom)
    return Music
}

let instance = null
// 创建组件实例，用于调用组件方法
const getInstance = () => {
    if (!instance) {
        instance = insertComponent()
    }
    return instance
}

MusicPlayer.songList = []
MusicPlayer.currentIndex = 0

MusicPlayer.initSongList = (list) => {
    // 初始化播放列表
    MusicPlayer.songList = list
    MusicPlayer.currentIndex = 0
}

MusicPlayer.pre = () => {
    // 上一曲
    const index = MusicPlayer.currentIndex - 1
    if (index >= 0) {
        MusicPlayer.currentIndex = MusicPlayer.currentIndex - 1
        MusicPlayer.init(MusicPlayer.songList[MusicPlayer.currentIndex])
    } else {
        // 当前是第一个, 转至最后一个
        MusicPlayer.currentIndex = MusicPlayer.songList.length - 1
        MusicPlayer.init(MusicPlayer.songList[MusicPlayer.currentIndex])
    }
}

MusicPlayer.next = () => {
    // 下一曲
    const index = MusicPlayer.currentIndex + 1
    if (index < MusicPlayer.songList.length) {
        console.log(MusicPlayer.songList[index])
        MusicPlayer.currentIndex = index
        MusicPlayer.init(MusicPlayer.songList[index])
    } else {
        // 当前是最后一个, 转至第一个
        MusicPlayer.currentIndex = 0
        MusicPlayer.init(MusicPlayer.songList[0])
    }
}

MusicPlayer.init = async (hash) => {
    // 通过 hash 获取音频信息，然后调用 Music init 方法初始化audio信息，并播放
    MusicPlayer.currentIndex = MusicPlayer.songList.indexOf(hash)
    const Music = getInstance()
    const data = await getSongInfo(hash)
    const { songName, singerName } = data
    const src = data.backup_url[0]
    if (src === undefined) {
        // 版权限制，暂时不能播放
    } else {
        const cover = createImageUrl(data.imgUrl, 400)
        Music.initFn(cover, songName, singerName, src)
    }
}

MusicPlayer.install = (app) => {
    app.config.globalProperties.$Music = MusicPlayer
}

export default MusicPlayer
